from django.db import transaction
from rest_framework.views import APIView
from rest_framework import generics
from utils import response_ok, response_error
from utils.custom_modelviewset import CustomModelViewSet
from utils.wechat_applet import WeChatApplet
from utils.permission import IsMemberUser
from .serializers import SendSmsSerializer, MemberMobileSignSerializer, MemberHouseSerializer, MemberRecordSerializer, \
    MemberSignSerializer
from .models import MemberHouse, MemberRecord


class RegisterView(APIView):
    serializer_class = MemberSignSerializer

    def post(self, request, *args, **kwargs):
        """账号密码中注册"""
        with transaction.atomic():
            ser = self.serializer_class(data=request.data)
            if ser.is_valid():
                return response_ok(ser.validated_data)
            return response_error('手机号或者密码错误！')


class MemberLoginView(APIView):
    # 验证码注册登录
    serializer_class = MemberMobileSignSerializer

    def post(self, request, *args, **kwargs):
        """验证码注册登录"""
        with transaction.atomic():
            ser = self.serializer_class(data=request.data)
            if ser.is_valid():
                return response_ok(ser.validated_data)
            return response_error('手机号或者验证码错误！')


class MemberSendCodeView(APIView):
    '''发送验证码'''
    serializer_class = SendSmsSerializer

    def post(self, request, *args, **kwargs):
        ser = self.serializer_class(data=request.data)
        if ser.is_valid():
            return response_ok('发送成功！')
        return response_ok(ser.errors['mobile'][0])


class GetWXCodeView(APIView):
    def get(self, request, *args, **kwargs):
        wechat_applet = WeChatApplet()
        wechat_applet.get_wx_acode_unlimit()
        return response_ok()


class MemberHouseViewSet(CustomModelViewSet):
    permission_classes = [IsMemberUser, ]
    queryset = MemberHouse.objects.filter()
    serializer_class = MemberHouseSerializer

    def get_queryset(self):
        return MemberHouse.objects.filter(member=self.request.user.member)

    def paginate_queryset(self, queryset):
        return None


class MeCollectionsView(generics.ListAPIView):
    permission_classes = [IsMemberUser, ]
    queryset = MemberRecord.objects.filter()
    serializer_class = MemberRecordSerializer

    def get_queryset(self):
        return MemberRecord.objects.filter(member=self.request.user.member, operate=MemberRecord.COLLECT)
